<template>
  <div>
    <h1>用户中心</h1>

    <!-- 显示用户当前信息 -->
    <div>
      <p>昵称: <input v-model="user.nickname" /></p>
      <p>邮箱: <input v-model="email" /></p>
      <p>手机号: <input v-model="phoneNumber" /></p>
    </div>

    <h2>修改邮箱</h2>
    <div>
      <input v-model="newEmail" placeholder="新邮箱" />
      <input v-model="currentPassword" type="password" placeholder="当前密码" />
      <button @click="updateEmail">更新邮箱</button>
    </div>

    <h2>修改手机号</h2>
    <div>
      <input v-model="newPhoneNumber" placeholder="新手机号" />
      <input v-model="currentPasswordForPhone" type="password" placeholder="当前密码" />
      <button @click="updatePhone">更新手机号</button>
    </div>

    <h2>修改密码</h2>
    <div>
      <input v-model="currentPasswordForUpdate" type="password" placeholder="当前密码" />
      <input v-model="newPassword" type="password" placeholder="新密码" />
      <button @click="updatePassword">更新密码</button>
    </div>

    <p v-if="message">{{ message }}</p>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      user: {
        nickname: '',
        email: '',
        phoneNumber: ''
      },
      newEmail: '',
      newPhoneNumber: '',
      currentPassword: '',
      currentPasswordForPhone: '',
      currentPasswordForUpdate: '',
      newPassword: '',
      message: ''
    };
  },
  created() {
    this.loadUser(); // 加载用户信息
  },
  methods: {
    loadUser() {
      const user = localStorage.getItem('user');
      if (user) {
        this.user = JSON.parse(user);
        this.newEmail = this.user.email; // 设置新邮箱为当前邮箱
        this.newPhoneNumber = this.user.phoneNumber; // 设置新手机号为当前手机号
      }
    },
    async updateEmail() {
      if (!this.validateEmail(this.newEmail)) {
        this.message = '邮箱格式不正确或已被注册。';
        return;
      }

      try {
        const response = await axios.post('http://localhost:9090/student/update-email', {
          email: this.newEmail,
          currentPassword: this.currentPassword
        }, {
          headers: {
            'Content-Type': 'application/json' // 确保请求头正确
          }
        });

        if (response.status === 200) {
          this.user.email = this.newEmail; // 更新用户信息
          localStorage.setItem('user', JSON.stringify(this.user)); // 更新 localStorage
          this.message = '邮箱更新成功';
        }
      } catch (error) {
        this.handleError(error, '更新邮箱失败');
      }
    },

    async updatePhone() {
      if (!this.validatePhone(this.newPhoneNumber)) {
        this.message = '手机号格式不正确或已被注册。';
        return;
      }

      try {
        const response = await axios.post('http://localhost:9090/student/update-phone', {
          phoneNumber: this.newPhoneNumber,
          currentPassword: this.currentPasswordForPhone
        }, {
          headers: {
            'Content-Type': 'application/json' // 确保请求头正确
          }
        });

        if (response.status === 200) {
          this.user.phoneNumber = this.newPhoneNumber; // 更新用户信息
          localStorage.setItem('user', JSON.stringify(this.user)); // 更新 localStorage
          this.message = '手机号更新成功';
        }
      } catch (error) {
        this.handleError(error, '更新手机号失败');
      }
    },

    async updatePassword() {
      try {
        const response = await axios.post('http://localhost:9090/student/update-password', {
          email: this.user.email, // 传递当前用户邮箱
          currentPassword: this.currentPasswordForUpdate,
          newPassword: this.newPassword
        }, {
          headers: {
            'Content-Type': 'application/json' // 确保请求头正确
          }
        });

        if (response.status === 200) {
          this.message = '密码更新成功';
        }
      } catch (error) {
        this.handleError(error, '更新密码失败');
      }
    },

    validateEmail(email) {
      const emailPattern = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
      return emailPattern.test(email); // 验证邮箱格式
    },

    validatePhone(phoneNumber) {
      const phonePattern = /^\d{11}$/;
      return phonePattern.test(phoneNumber); // 验证手机号格式
    },

    handleError(error, defaultMessage) {
      if (error.response) {
        console.error("响应错误:", error.response.data);
        console.error("响应状态:", error.response.status);
        this.message = error.response.data.message || defaultMessage; // 使用后端返回的错误信息
      } else if (error.request) {
        console.error("请求发送，但没有响应:", error.request);
        this.message = '未收到后端响应，可能是网络问题。';
      } else {
        console.error("其他错误:", error.message);
        this.message = defaultMessage;
      }
    }
  }
};
</script>

<style scoped>
/* 在这里添加样式 */
</style>
